<template>
    <div>
        <!-- 添加/修改页面 -->
        <el-card shadow="always" :body-style="{ padding: '20px' }" style="margin: 10px 0;">
            <el-form :inline="false">
                <el-form-item label="SPU名称">
                    <el-input v-model="spuParams.spuName" placeholder="请输入SPU名称"></el-input>
                </el-form-item>
                <el-form-item label="SPU品牌">
                    <el-select v-model="spuParams.tmId" placeholder="请选择" clearable filterable>
                        <el-option :label="item.tmName" :value="item.id" v-for="(item,index) in trademarkArr"
                            :key="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="SPU描述">
                    <el-input v-model="spuParams.description" placeholder="请输入SPU描述" type="textarea" clearable>
                    </el-input>
                </el-form-item>
                <el-form-item label="SPU图片">
                    <el-upload v-model:file-list="imgList" action="/api/admin/product/fileUpload"
                        list-type="picture-card" :on-preview="handlePictureCardPreview" :on-remove="handleRemove">
                        <el-icon>
                            <Plus />
                        </el-icon>
                    </el-upload>
                    <el-dialog v-model="dialogVisible">
                        <img w-full :src="dialogImageUrl" alt="Preview Image" />
                    </el-dialog>
                </el-form-item>
                <el-form-item label="销售属性">
                    <el-select v-model="unSaleAttrNameAndId"
                        :placeholder="unSelectSaleAttr.length>0?`您还有${unSelectSaleAttr.length}没有选`:'没得选啦'" clearable
                        filterable>
                        <el-option :label="item.name" :value="`${item.id}:${item.name}`"
                            v-for="(item,index) in unSelectSaleAttr" :key="item.id"></el-option>
                    </el-select>
                    <el-button type="primary" size="default" :icon="Plus" @click="addAttrValue"
                        style="margin-left: 10px;" :disabled="unSelectSaleAttr.length==0">添加销售属性
                    </el-button>

                    <el-table border stripe style="margin:10px 0;" :data="saleAttrList">
                        <el-table-column label="序号" width="80" align="center" type="index"></el-table-column>
                        <el-table-column label="属性名" width="160" prop="saleAttrName"></el-table-column>
                        <el-table-column label="属性值列表">
                            <template v-slot="{row,$index}">
                                <el-tag v-for="(tag,index) in row.spuSaleAttrValueList" :key="tag.id" class="mx-1"
                                    closable style="margin-right: 10px;"
                                    @close="row.spuSaleAttrValueList.splice($index,1)">
                                    {{ tag.saleAttrValueName }}
                                </el-tag>
                                <el-input ref="inputRef" v-if="row.flag" v-model="row.inputValue" placeholder="请输入属性值"
                                    size="small" style="width: 100px" clearable @blur="toLook(row)"></el-input>
                                <el-button v-else type="primary" size="small" :icon="Plus" @click="toEdit(row)">
                                </el-button>

                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="160">
                            <template v-slot="{row,$index}">
                                <el-button type="danger" size="small" :icon="Delete"
                                    @click="saleAttrList.splice($index,1)"></el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <el-button type="primary" size="default" @click="save">保存</el-button>
                    <el-button size="default" @click="cancel">取消</el-button>
                </el-form-item>
            </el-form>
        </el-card>

    </div>
</template>

<script setup lang="ts">
import { Plus, Delete } from '@element-plus/icons-vue'
import { reqAllTrademark, reqAllAttr, reqImageList, reqSaleAttr, reqAddOrUpdateSpu } from '@/api/product/spu/spu'
import type { UploadProps, UploadUserFile } from 'element-plus'
import { ElMessage } from 'element-plus'
import { reactive, ref, computed, nextTick } from 'vue';

// 存储全部品牌
let trademarkArr = ref([])
// 存储全部销售属性
let allAttrArr = ref([])
// 存储已有spu照片墙
let imgList = ref([])
// 存储spu已有的销售属性
let saleAttrList = ref([])
// 存储spu数据
let spuParams = ref({
    // spuName: '',
    // description: '',
    // category3Id: categoryStore.c3Id,
    // tmId: '',
    // spuImageList: [],
    // spuSaleAttrList: []
})

// 存储未选中的属性的名字和id
let unSaleAttrNameAndId = ref('')
// 存储input中输入的值
let inputValue = ref()
// 存储input实例
let inputRef = ref()

// 照片墙
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
// 删除图片的回调
const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
    console.log(uploadFile, uploadFiles)
    // 存储删除后剩下的图片
    imgList.value = uploadFiles
}
// 预览回调
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url!
    dialogVisible.value = true
}

// 获取所有数据
const getSpuAllInfo = async (spu) => {
    // 存储spu数据
    spuParams.value = spu
    // 获取全部品牌
    let ps1 = reqAllTrademark()
    // 获取全部销售属性
    let ps2 = reqAllAttr()
    // 获取已有spu照片墙
    let ps3 = reqImageList(spu.id)
    // 获取spu已有的销售属性
    let ps4 = reqSaleAttr(spu.id)
    let result = await Promise.all([ps1, ps2, ps3, ps4])
    console.log(result);
    // 存储全部品牌
    trademarkArr.value = result[0]
    // 存储全部销售属性
    allAttrArr.value = result[1]
    // 存储已有spu照片墙
    //当服务器数据返回需要对数据进行处理
    imgList.value = result[2].map((item) => {
        return {
            name: item.imgName,
            url: item.imgUrl
        }
    })
    // 存储spu已有的销售属性
    saleAttrList.value = result[3]

}

// 点击添加属性值按钮
const addAttrValue = () => {
    //整理参数
    //新增的销售属性ID与名字
    const [baseSaleAttrId, saleAttrName] = unSaleAttrNameAndId.value.split(":");
    //服务器需要销售属性对象
    let newSaleAttr = { baseSaleAttrId, saleAttrName, spuSaleAttrValueList: [] };
    //向SPU已有的数组里面追加新增销售是属性
    saleAttrList.value.push(newSaleAttr);
    //清空下拉框的数据
    unSaleAttrNameAndId.value = '';
}

// 计算剩下的全部属性个数
const unSelectSaleAttr = computed(() => {
    let result = allAttrArr.value.filter((item) => {
        return saleAttrList.value.every((item1) => {
            return item.name != item1.saleAttrName
        })
    })
    return result
})

// input失去焦点时的回调
const toLook = (row) => {
    // 如果输入的为空
    if (row.inputValue.trim() == '') {
        ElMessage({
            type: 'error',
            message: '属性值不能为空'
        })
        return
    }

    // 如果输入的值是重复的
    let repeat = row.spuSaleAttrValueList.find((item) => {
        return item.saleAttrValueName === row.inputValue
    })

    if (repeat) {
        ElMessage({
            type: 'warning',
            message: '输入的内容出现重复'
        })
        row.inputValue = ''
        // 显示button按钮
        row.flag = false
        return
    }


    // 显示button按钮
    row.flag = false

    // 整理数据新增属性值
    let newSaleAttrVal = {
        baseSaleAttrId: row.baseSaleAttrId,
        saleAttrValueName: row.inputValue,
    }
    row.spuSaleAttrValueList.push(newSaleAttrVal)
    // 清空数据
    row.inputValue = ''
}

// 点击按钮切换编辑模式
const toEdit = (row) => {
    row.flag = true
    // 初始值为空
    row.inputValue = ''
}

// 点击保存按钮发请求
const save = async () => {
    // 整理参数
    // 整理照片墙参数
    spuParams.value.spuImageList = imgList.value.map((item) => {
        return {
            imgName: item.name,
            imgUrl: (item.response && item.response.data) || item.url
        }
    })
    // 整理属性值参数
    spuParams.value.spuSaleAttrList = saleAttrList.value
    try {
        await reqAddOrUpdateSpu(spuParams.value)
        ElMessage({
            type: 'success',
            message: spuParams.value.id ? '修改成功' : '添加成功'
        })
        // 触发自定义事件
        emit('changeShow', { shows: 0, flag: spuParams.value.id ? "update" : "add", })
        resetData()
    } catch (error) {
        ElMessage({
            type: 'error',
            message: spuParams.value.id ? '修改失败' : '添加失败'
        })
    }

}
// 点击取消按钮
const cancel = () => {
    resetData()
    emit('changeShow', { shows: 0, flag: spuParams.value.id ? "update" : "add", })
}

// 添加spu
const initAddSpu = async (c3Id:string|number) => {
    // 获取三级分类的id
    spuParams.value.category3Id = c3Id
    // 获取全部品牌
    let ps1 = reqAllTrademark()
    // 获取全部销售属性
    let ps2 = reqAllAttr()
    let result = await Promise.all([ps1, ps2])
    console.log(result);
    // 存储全部品牌
    trademarkArr.value = result[0]
    // 存储全部销售属性
    allAttrArr.value = result[1]
}

// 清空数据的回调
const resetData = () => {
    spuParams.value = {}
    imgList.value = []
    saleAttrList.value = []
}

// 触发自定义事件
let emit = defineEmits(['changeShow'])

// 对外暴露方法
defineExpose({
    getSpuAllInfo,
    initAddSpu
})
</script>

<style scoped>

</style>